import { onBeforeUnmount, onMounted, ref } from 'vue';

export function useBroadcastChannel(channelName) {
  const channel = ref();
  const data = ref();
  const error = ref(null);

  onMounted(() => {
    console.log('onMounted');
    try {
      channel.value = new BroadcastChannel(channelName);
      channel.value.onmessage = (event) => {
        console.log('xxx', event);
        data.value = event.data;
      };
    } catch (e) {
      error.value = e;
    }
  });

  onBeforeUnmount(() => {
    close();
  });

  const post = (data) => {
    if (channel.value) {
      console.log('post', data, channel);
      channel.value.postMessage(data);
    }
  };

  const close = () => {
    if (channel.value) {
      channel.value.close();
    }
  };

  return {
    channel,
    data,
    post,
    close,
    error,
  };
}
